#!/usr/local/python
# -*- coding: utf-8 -*-
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import xlrd
import utils
# Step 1: read in data from the .xls file
book = xlrd.open_workbook('fire_theft.xls', encoding_override="utf-8")
sheet = book.sheet_by_index(0)
data = np.asarray([sheet.row_values(i) for i in range(1, sheet.nrows)])
n_samples = sheet.nrows - 1
# Step 2: create placeholders for input X (number of fire) and label Y (number of theft)
X = tf.placeholder(tf.float32, name='X')
Y = tf.placeholder(tf.float32, name='Y')

v = tf.placeholder(tf.float32)
sv = tf.placeholder(tf.float32)
# Step 3: create weight and bias, initialized to 0

#w = tf.Variable(0.0, name='weights')
#b = tf.Variable(0.0, name='ias')

w = tf.Variable(0.0, name='weights_1')
u = tf.Variable(0.0, name='weights_2')
b = tf.Variable(0.0, name='bias')



# Step 4: build model to predict
#Y_predicted = X * X *  w +X * u+ b
#Y_predicted = X*X*w+X*u+b
Y_predicted = X*w+b
# Step 5: use the square error as the loss function
#loss = tf.square(Y - Y_predicted, name='loss')
loss = utils.huber_loss(Y, Y_predicted)
tf.summary.scalar('meanv',v)
tf.summary.scalar('sumv',sv)
merge_op=tf.summary.merge_all()# 有多个监控变量时用这个，单个变量merge_op=tf.summary.scalar('sumv',sv)
ls=[0]*40
# Step 6: using gradient descent with learning rate of 0.001 to minimize loss# learning_rate为0.01 训练不出来
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(loss)
with tf.Session() as sess:
	# Step 7: initialize the necessary variables, in this case, w and b
	sess.run(tf.global_variables_initializer())
	writer = tf.summary.FileWriter('./graphs/linear_reg', sess.graph)
	# Step 8: train the model
	for i in range(40): # train the model 100 epochs
		total_loss = 0

		for x, y in data:
			# Session runs train_op and fetch values of loss
			#sess.run(optimizer, feed_dict={X: x, Y:y})
			_,los= sess.run([optimizer, loss], feed_dict={X: x, Y:y})
			total_loss+=los
		lo=total_loss/n_samples
		ls[i]=lo
		summary=sess.run(merge_op, feed_dict={v:lo,sv:total_loss})
		writer.add_summary(summary,i)
		writer.flush()
	# close the writer when you're done using it
	writer.close()
	# Step 9: output the values of w and b
	w,b= sess.run([w,b])
# plot the results
print w,b,ls
X, Y = data.T[0], data.T[1]
plt.plot(X, Y, 'bo', label='Real data')
plt.plot(X, X*w+ b, 'ro', label='Predicted data')
x1=np.arange(40)
plt.plot(x1, ls, 'yo', label='loss')
#plt.plot(X, X*X*w+X*u+ b, 'r', label='Predicted data')
plt.legend()
plt.show()